package com.bj58.ecdata.dashboard.databll;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;

import com.bj58.ecdata.dashboard.cache.ServiceBeanFactory;
import com.bj58.ecdata.dashboard.dbentity.IncomeKPIBusinessAll;
import com.bj58.ecdata.dashboard.dbentity.IncomeKPIBusinessUp;
import com.bj58.ecdata.dashboard.dbentity.IncomeKPIOnlineAll;
import com.bj58.ecdata.dashboard.service.AbstractBaseService;
import com.bj58.ecdata.dashboard.utils.ReflectUtil;

public class IncomeKPIBLL {

	private static AbstractBaseService<IncomeKPIBusinessAll> incomeKPIBusinessAllService = ServiceBeanFactory.get(
			IncomeKPIBusinessAll.class, null);

	private static AbstractBaseService<IncomeKPIOnlineAll> incomeKPIOnlineAll = ServiceBeanFactory.get(
			IncomeKPIOnlineAll.class, null);

	private static AbstractBaseService<IncomeKPIBusinessUp> incomeKPIBusinessUp = ServiceBeanFactory.get(
			IncomeKPIBusinessUp.class, null);

	public static String getOnlineJson(String type) {
		List<IncomeKPIOnlineAll> result = incomeKPIOnlineAll.getListByConditon("*",
				String.format("stat_type='%s'", type), null);
		// 数据错误 造假数据
		// for (IncomeKPIOnlineAll a : result) {
		// a.setQtr_num(a.getMonth_num());
		// a.setMonth_num(a.getTime_rate().substring(0, 6));
		// a.setTime_rate("1");
		// }

		String group = "";
		if (StringUtils.equalsIgnoreCase(type, "month")) {
			group = "month_num";
		} else if (StringUtils.equalsIgnoreCase(type, "quarter")) {
			group = "qtr_num";
		} else {
			return null;
		}
		Map<String, List<IncomeKPIOnlineAll>> map = ReflectUtil.groupByField(result, group);

		JSONObject json = new JSONObject();

		json.accumulate("timeline", JSONArray.fromObject(map.keySet()));

		JSONObject json2 = new JSONObject();
		for (String key : map.keySet()) {
			json2.accumulate(key, JSONArray.fromObject(map.get(key)));
		}
		json.accumulate("options", json2);
		return json.toString();
	}

	public static String getBusinessJson(String type) {

		List<IncomeKPIBusinessAll> result = incomeKPIBusinessAllService.getListByConditon("*",
				String.format(where_bar, type), null);

		// 先按时间分组
		String group_time = "";
		if (StringUtils.equalsIgnoreCase(type, "month")) {
			group_time = "month_num";
		} else if (StringUtils.equalsIgnoreCase(type, "quarter")) {
			group_time = "qtr_num";
		} else {
			return null;
		}

		// 返回总对象
		JSONObject json = new JSONObject();

		//   按时间分
		Map<String, List<IncomeKPIBusinessAll>> map = ReflectUtil.groupByField(result, group_time);

		// 两个图时间timeline一样
		JSONArray timeline = JSONArray.fromObject(map.keySet());
		json.accumulate("timeline", timeline);

		JSONObject json2 = new JSONObject();
		for (String key : map.keySet()) {
			JSONObject json3 = new JSONObject();

			json3.accumulate("business", getJsonObjByList(map.get(key), "business_type"));
			json3.accumulate("product", getJsonObjByList(map.get(key), "product_type"));

			json2.accumulate(key, json3);
		}
		json.accumulate("options", json2);
		// JSONObject json = new JSONObject();
		// json.accumulate("pie", getPieJson(type));
		//
		// JSONObject o = getBarJson(type);
		// Iterator<String> it = o.keys();
		// while (it.hasNext()) {
		// String key = it.next();
		// json.accumulate(key, o.getJSONObject(key));
		// }
		//
		return json.toString();
	}

	private static JSONObject getJsonObjByList(List<IncomeKPIBusinessAll> list, String groupByField) {

		Map<String, List<IncomeKPIBusinessAll>> map = ReflectUtil.groupByField(list, groupByField);

		JSONObject result = new JSONObject();
		for (String key : map.keySet()) {
			result.accumulate(key, JSONArray.fromObject(map.get(key)));
		}
		return result;
	}

	private static final String where_trend = "stat_type='%s' AND product_type='%s'";

	public static String getBusinessJsonTrend(String type, String busiType) {

		List<IncomeKPIBusinessAll> result0 = incomeKPIBusinessAllService.getListByConditon("*",
				String.format(where_trend, type, busiType), "stat_date");

		String group = "";
		if (StringUtils.equalsIgnoreCase(type, "month")) {
			group = "month_num";
		} else if (StringUtils.equalsIgnoreCase(type, "day")) {
			group = "stat_date";
		} else {
			return null;
		}
		Map<String, List<IncomeKPIBusinessAll>> map = ReflectUtil.groupByField(result0, group);

		JSONObject json = new JSONObject();
		json.element("time", map.keySet());

		Map<String, List<Integer>> result = new HashMap<String, List<Integer>>();
		for (String key : map.keySet()) {
			List<IncomeKPIBusinessAll> list = map.get(key);
			for (IncomeKPIBusinessAll a : list) {
				if (!result.containsKey(a.getBusinessTypeName())) {
					result.put(a.getBusinessTypeName(), new ArrayList<Integer>());
				}
				result.get(a.getBusinessTypeName()).add(a.getCash());
			}
		}

		json.element("legend", result.keySet());

		JSONObject data = new JSONObject();
		for (String key : result.keySet()) {
			data.element(key, JSONArray.fromObject(result.get(key)));
		}
		json.element("data", data);
		return json.toString();
	}

	public static String getOnlineJsonTrend(String type) {

		List<IncomeKPIOnlineAll> result0 = incomeKPIOnlineAll.getListByConditon("*", String.format(where_bar, type),
				"stat_date");

		String group = "";
		if (StringUtils.equalsIgnoreCase(type, "month")) {
			group = "month_num";
		} else if (StringUtils.equalsIgnoreCase(type, "day")) {
			group = "stat_date";
		} else {
			return null;
		}
		Map<String, List<IncomeKPIOnlineAll>> map = ReflectUtil.groupByField(result0, group);

		JSONObject json = new JSONObject();
		json.element("time", map.keySet());

		Map<String, List<Integer>> result = new HashMap<String, List<Integer>>();
		for (String key : map.keySet()) {
			List<IncomeKPIOnlineAll> list = map.get(key);
			for (IncomeKPIOnlineAll a : list) {
				if (StringUtils.equals(a.getProduct_type(), "all")) {
					continue;
				}
				if (!result.containsKey(a.getProductTypeName())) {
					result.put(a.getProductTypeName(), new ArrayList<Integer>());
				}
				result.get(a.getProductTypeName()).add(a.getCash());
			}
		}

		json.element("legend", result.keySet());

		JSONObject data = new JSONObject();
		for (String key : result.keySet()) {
			data.element(key, JSONArray.fromObject(result.get(key)));
		}
		json.element("data", data);
		return json.toString();
	}

	private static final String where_pie = "stat_type='%s' AND product_type='all'";

	public static JSONObject getPieJson(String type) {

		List<IncomeKPIBusinessAll> result = incomeKPIBusinessAllService.getListByConditon("*",
				String.format(where_pie, type), null);

		String group = "";
		if (StringUtils.equalsIgnoreCase(type, "month")) {
			group = "month_num";
		} else if (StringUtils.equalsIgnoreCase(type, "quarter")) {
			group = "qtr_num";
		} else {
			return null;
		}
		Map<String, List<IncomeKPIBusinessAll>> map = ReflectUtil.groupByField(result, group);

		JSONObject json = new JSONObject();

		json.accumulate("timeline", JSONArray.fromObject(map.keySet()));

		JSONObject json2 = new JSONObject();
		for (String key : map.keySet()) {
			json2.accumulate(key, JSONArray.fromObject(map.get(key)));
		}
		json.accumulate("options", json2);
		return json;

	}

	private static final String col_bar = "stat_type,time_rate,month_num,qtr_num,business_type,product_type,avg_bal,complete_rate,fore_rate";

	private static final String where_bar = "stat_type='%s'";

	/**
	 * 柱形图
	 * 
	 * @param type
	 *            --月或者季度
	 * @return
	 */
	public static JSONObject getBarJson(String type) {
		// 查询两个图的所有数据
		List<IncomeKPIBusinessAll> result = incomeKPIBusinessAllService.getListByConditon(col_bar,
				String.format(where_bar, type), null);

		// 先按时间分组
		String group_time = "";
		if (StringUtils.equalsIgnoreCase(type, "month")) {
			group_time = "month_num";
		} else if (StringUtils.equalsIgnoreCase(type, "quarter")) {
			group_time = "qtr_num";
		} else {
			return null;
		}

		// 返回总对象
		JSONObject json = new JSONObject();

		JSONObject json_bar = new JSONObject();

		//   按时间分
		Map<String, List<IncomeKPIBusinessAll>> map = ReflectUtil.groupByField(result, group_time);

		// 两个图时间timeline一样
		JSONArray timeline = JSONArray.fromObject(map.keySet());
		json_bar.accumulate("timeline", timeline);

		JSONObject options_bar = new JSONObject();

		// 处理每个时间线的数据
		for (String key : map.keySet()) {
			//   按时间分组后按business_type分组
			List<IncomeKPIBusinessAll> list = map.get(key);
			Map<String, List<IncomeKPIBusinessAll>> map_busi = ReflectUtil.groupByField(list, "business_type");

			// 处理bar
			JSONArray arr = new JSONArray();
			for (String keybusi : map_busi.keySet()) {
				JSONObject json_bar_ser = new JSONObject();
				json_bar_ser.accumulate("name", map_busi.get(keybusi).get(0).getBusinessTypeName());
				JSONArray data_arr = new JSONArray();
				for (IncomeKPIBusinessAll in : map_busi.get(keybusi)) {
					if (StringUtils.equalsIgnoreCase(in.getProduct_type(), "zhineng")) {
						continue;
					}
					data_arr.add(in.getAvg_bal());
				}
				json_bar_ser.accumulate("data", data_arr);
				arr.add(json_bar_ser);
			}
			options_bar.accumulate(key, arr);

		}

		json_bar.accumulate("options", options_bar);
		json.accumulate("bar", json_bar);

		// 以下处理mutibar
		JSONObject json_mutibar = new JSONObject();

		Map<String, List<IncomeKPIBusinessAll>> map_product = ReflectUtil.groupByField(result, "product_type");

		for (String key : map_product.keySet()) {
			if (StringUtils.equalsIgnoreCase(key, "zhineng")) {
				continue;
			}

			List<IncomeKPIBusinessAll> list = map_product.get(key);
			Map<String, List<IncomeKPIBusinessAll>> map_product_in = ReflectUtil.groupByField(list, group_time);

			JSONObject json3 = new JSONObject();
			json3.accumulate("timeline", JSONArray.fromObject(map_product_in.keySet()));

			JSONObject options = new JSONObject();
			for (String key_in : map_product_in.keySet()) {
				JSONObject option = new JSONObject();
				option.accumulate("time_rate", map_product_in.get(key_in).get(0).getTime_rate());
				JSONArray complete = new JSONArray();
				JSONArray fore = new JSONArray();

				for (IncomeKPIBusinessAll a : map_product_in.get(key_in)) {
					complete.add(a.getComplete_rate());
					fore.add(a.getFore_rate());
				}

				option.accumulate("complete_rate", complete);
				option.accumulate("fore_rate", fore);
				options.accumulate(key_in, option);
			}
			json3.accumulate("options", options);
			json_mutibar.accumulate(key, json3);
		}

		json.accumulate("mutibar", json_mutibar);
		return json;

	}

	public static String getBusinessUpJson(String type, String time) {

		String where = "stat_type='%s' and ";
		if (StringUtils.equals(type, "month")) {
			where += "month_num='%s'";
			where = String.format(where, type, time);
		} else if (StringUtils.equals(type, "week")) {
			List<String> weeks = getWeeks(time);
			where += "start_date ='%s' and end_date='%s'";
			where = String.format(where, type, weeks.get(0), weeks.get(1));
		}

		List<IncomeKPIBusinessUp> result = incomeKPIBusinessUp.getListByConditon("*", where, null);

		Map<String, List<IncomeKPIBusinessUp>> map = ReflectUtil.groupByField(result, "business_type");

		JSONObject json = new JSONObject();

		for (String key : map.keySet()) {
			JSONObject in = new JSONObject();
			for (IncomeKPIBusinessUp up : map.get(key)) {
				in.accumulate(up.getProduct_type(), JSONObject.fromObject(up));
			}
			json.accumulate(key, in);
		}
		return json.toString();

	}

	private static List<String> getWeeks(String time) {

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		try {
			Date date = sdf.parse(time);
			Calendar cl = Calendar.getInstance();
			cl.setTime(date);
			int day = cl.get(Calendar.DAY_OF_WEEK);

			Date begin;
			Date end;
			if (day >= 6) {
				begin = DateUtils.addDays(date, 6 - day);
				end = DateUtils.addDays(date, 12 - day);
			} else {
				begin = DateUtils.addDays(date, -day - 1);
				end = DateUtils.addDays(date, 5 - day);
			}

			List<String> list = new ArrayList<String>();
			list.add(sdf.format(begin));
			list.add(sdf.format(end));
			return list;
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return Collections.emptyList();
	}
}
